package cn.itsource.upload.service.imp;

import cn.hutool.core.io.file.FileNameUtil;
import cn.itsource.upload.service.MinioIService;
import io.minio.BucketExistsArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
@Service
public class MinioIServiceImp implements MinioIService {
    @Value("${minio.bucketname}")
    private String bucketName;

    @Autowired
    private MinioClient minioClient;

    @Override
    public String upload(@RequestParam("file") MultipartFile file) throws IOException, ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //文件真实的名字  美女.jpg
        String originalFilename = file.getOriginalFilename();
        //获取文件的后缀
        String suffix = FileNameUtil.getSuffix(originalFilename);

        //给附件随机生成一个名字
        String newFileName = System.currentTimeMillis() + "." + suffix;
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(bucketName). //上传到哪一个桶
                        object(newFileName). //上传到服务器中文件的名称
                        stream(file.getInputStream(),//我要上传的附件
                        file.getSize(), -1) // 文件大小，不分片(不做分布式存储)
                .contentType(file.getContentType()) // 上传附件的类型
                .build();
        minioClient.putObject(args);
        String filePath = bucketName + "/" + newFileName;
        return filePath;
    }

    @Override
    public void delete(String fileName) throws ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //判断桶是否存在
        boolean res=minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (res) {
            //删除文件
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName)
                    .object(fileName).build());
        }
    }
}
